<template>
  <div class="update-gender">
    <van-picker
      show-toolbar
      title="标题"
      :columns="columns"
      :default-index="value"
      @cancel="$emit('close')"
      @confirm="onConfirm"
      @change="onPickerChange"
    />
  </div>
</template>

<script>
import { updateUserProfile } from '@/assets/api/user';

export default {
  name: 'UpdateGender',
  components: {},
  props: {
    // 用户性别
    value: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      // 性别选择数据源
      columns: ['男', '女'],
      // 选中的性别
      localGender: this.value
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 完成按钮点击事件
    async onConfirm() {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      });

      try {
        const localGender = this.localGender;

        await updateUserProfile({
          gender: localGender
        });

        // 更新视图
        this.$emit('input', localGender);

        // 关闭弹层
        this.$emit('close');

        // 提示成功
        this.$toast.success('更新成功');
      } catch (err) {
        this.$toast.fail('更新失败');
      }
    },
    // picker 滚动回调
    onPickerChange(picker, value, index) {
      this.localGender = index;
    }
  }
};
</script>

<style scoped lang="less"></style>
